import type { Module } from 'vuex'
import router from '@/router'
import type { ITagsState } from './types'
import type { IRootState } from '../types'

const tags: Module<ITagsState, IRootState> = {
  namespaced: true,
  state() {
    return {
      tagList: [],
      keepLiveRoute: [],
      // 上次移动的标签的索引
      lastDragEndIndex: 0
    }
  },
  mutations: {
    // 添加
    pushTags(state, route) {
      const target = state.tagList.find((item) => item.fullPath === route.fullPath)
      const hasName = route.name
      if (!target && hasName) {
        state.tagList.push(route)
      }
    },
    // 关闭
    removeTags(state, path) {
      state.tagList.forEach((item, index) => {
        if (item.path === path) {
          state.tagList.splice(index, 1)

          if (!state.tagList[index]) {
            if (index > 1) {
              router.push({ path: state.tagList[index - 1].path })
            } else {
              router.push({ path: '/dashboard/analysis' })
            }
          }
        }
      })
    },
    // 排序
    sortTags(state, { oldIndex, newIndex }) {
      const currentTab = state.tagList[oldIndex]
      state.tagList.splice(oldIndex, 1)
      state.tagList.splice(newIndex, 0, currentTab)
      state.lastDragEndIndex = state.lastDragEndIndex + 1
    },
    pushKeepLive(state, route) {
      if (!state.keepLiveRoute.includes(route)) {
        state.keepLiveRoute.push(route)
      }
    }
  }
}

export default tags
